<?php

namespace app\api\services;


/**
 * Class TengxunMap
 * @package app\api\services\jizhan
 * @desc 腾讯地图相关API服务
 */
class TengxunMap
{
    use \app\api\services\ApiTrait;

    public $key = 'F2GBZ-SREWQ-A3K56-GSLK5-ELOHS-PRB2X';

    //获取2点之间的距离
    public function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $url = sprintf('http://apis.map.qq.com/ws/distance/v1/?mode=driving&from=%s,%s&to=%s,%s&key=%s', $lat1, $lng1, $lat2, $lng2, $this->key);
        $r2  = file_get_contents($url);
        $res = json_decode($r2, true);
        if ($res['status'] == 0) {
            $result   = $res['result'];
            $elements = $result['elements'][0];
            if ($elements['distance'] > 5000) {
                return $this->returnArr(0, '当前位置不在服务范围,超出距离5km,距离' . $elements['distance'], $elements['distance']);
            }
            return $this->returnArr(1, '计算两点距离:' . $elements['distance'] . '米', $elements['distance']);
        } else {
            return $this->returnArr(0, '计算距离出错', $res);
        }
    }

    /**
     * @desc 地址转化为经纬度
     * @param $address
     */
    public function addressToLatlng($address)
    {
        $r = file_get_contents('http://apis.map.qq.com/ws/geocoder/v1/?address=' . $address . '&key=' . $this->key);
        $r = json_decode($r, true);
        if ($r['status'] == 0) {
            $ret['lng'] = $r['result']['location']['lng'];
            $ret['lat'] = $r['result']['location']['lat'];
            return $this->returnArr(1, '获取成功', $ret);
        } else {
            return $this->returnArr(0, '腾讯地图未查询到地址对应经纬度', $r['message']);
        }
    }

    /**
     * @desc 经纬度转化为地址
     * @param $address
     */
    public function lnglatToAddress($lng, $lat)
    {
        $ret     = [];
        $url     = 'https://apis.map.qq.com/ws/geocoder/v1/?location=' . $lat . ',' . $lng . '&key=' . $this->key . '&get_poi=0';
        $result  = file_get_contents($url);
        $starend = json_decode($result, true);
        if ($starend['status'] == 0) {
            $ret['lng']       = $starend['result']['location']['lng'];
            $ret['lat']       = $starend['result']['location']['lat'];
            $ret['address']   = $starend['result']['formatted_addresses'];
            $addressComponent = $starend['result']['address_component'];
            $ret['province']  = $addressComponent['province'];
            $ret['city']      = $addressComponent['city'];
            $ret['district']  = $addressComponent['district'];
            $ret['street']    = $addressComponent['street'];

            return $this->returnArr(1, '经纬度查询地址成功', $ret);
        } else {
            return $this->returnArr(0, '经纬度查询地址失败', $starend);
        }
    }
}